package cn.thornbird.orgsync.util;

import cn.thornbird.orgsync.entity.User;
import cn.thornbird.orgsync.model.UserData;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtil {

    public static boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && !(authentication instanceof AnonymousAuthenticationToken) &&
                authentication.isAuthenticated();
    }

    public static void updateAuthentication(User user) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Authentication newAuthentication = new UsernamePasswordAuthenticationToken(
                new UserData(user, null), authentication.getCredentials(), null);
        SecurityContextHolder.getContext().setAuthentication(newAuthentication);
    }

}
